<template>
    <div>
        <div style="margin-top: 15px">
            <van-icon name="arrow-left" class="arrow-left" @click="onClickLeft"/>
            <van-icon name="home" class="home"style="" @click="onClickHome"/>
        </div>
        <div class="goods">
            <van-swipe class="goods-swipe" :autoplay="3000">
                <van-swipe-item v-for="thumb in goods.thumb" :key="thumb">
                    <img :src="thumb">
                </van-swipe-item>
            </van-swipe>

            <van-cell-group>
                <van-cell>
                    <div class="goods-title">{{ goods.title }} <span class="goods-sub-title">{{ goods.subTitle }}</span>
                    </div>
                    <div class="goods-price">{{ priceRange }}</div>
                </van-cell>
                <van-cell class="goods-express">
                    <van-col span="10">运费：{{ goods.freightInfo }}</van-col>
                    <van-col span="14">成交：{{ goods.transactionNum }}</van-col>
                </van-cell>
            </van-cell-group>

            <van-cell-group class="goods-cell-group">
                <van-cell value="进入店铺" icon="shop" is-link @click="sorry">
                    <template slot="title">
                        <span class="van-cell-text" v-text="goods.shopName">有赞的店</span>
                        <van-tag class="goods-tag" type="danger">官方</van-tag>
                    </template>
                </van-cell>
            </van-cell-group>
            <van-cell-group class="goods-cell-group">
                <van-cell title="选择" is-link @click="onClickGoShopping"/>
                <van-cell title="参数" is-link @click="showParameter=true"/>
            </van-cell-group>

            <van-panel title="商品详情" desc="图文">
                <div class="goods-description" v-html="goods.description" ref="goods-description">内容</div>
            </van-panel>

            <van-goods-action>
                <van-goods-action-mini-btn icon="home" @click="$router.push('/home')">
                    首页
                </van-goods-action-mini-btn>
                <template v-if="bus.state.cartGoodsNum>0">
                    <van-goods-action-mini-btn icon="cart" :info="bus.state.cartGoodsNum" @click="onClickCart">
                        购物车
                    </van-goods-action-mini-btn>
                </template>
                <template v-else>
                    <van-goods-action-mini-btn icon="cart" @click="onClickCart">
                        购物车
                    </van-goods-action-mini-btn>
                </template>
                <van-goods-action-big-btn @click="onClickAddCart">
                    加入购物车
                </van-goods-action-big-btn>
                <van-goods-action-big-btn primary @click="onClickGoShopping">
                    立即购买
                </van-goods-action-big-btn>
            </van-goods-action>

        </div>

        <!--商品规格弹出层-->
        <van-sku
                v-model="showBase"
                :sku="sku"
                :goods="goods"
                :hide-stock="sku.hide_stock"

        >
            <div slot="sku-header-price">
                <div class="van-sku__goods-price" v-text="priceRange">￥ 1999.00</div>
            </div>
            <div slot="sku-group">
                <div class="van-sku-group-container van-hairline--bottom">
                    <div class="van-sku-row" v-for="item in goods.specifications" :key="item.name">
                        <div class="van-sku-row__title" v-text="item.name">顔色</div>
                        <span
                                class="van-sku-row__item "
                                v-for="value in item.values"
                                v-text="value.name"
                                :key="value.name"
                                :class="{'van-sku-row__item--disabled': value.noSelect, 'van-sku-row__item--active':item.selectedValue==value.name}"
                                @click="onSelectValue(item,value.name)"
                        >
                            黑色
                        </span>
                    </div>
                </div>
            </div>

            <div slot="sku-stepper">
                <div class="van-sku-stepper-stock" v-for="item in selectSkuArray" :key="item.id">
                    <div class="van-sku-stepper-container">
                        <div class="van-sku__stepper-title">{{item.color}} <span  style="color: #f44" >{{item.price | formatPrice}}</span>
                        </div>
                        <div class="van-sku__stepper van-stepper">
                            <van-stepper v-model="item.currentNum"
                                         :min="0"
                                         :max="item.stepperLimit"/>
                        </div>
                    </div>
                    <div class="van-sku__stock">库存{{item.stock}}件</div>
                    <div class="van-sku__quota" v-if="item.quota">本次限购{{item.quota}}件</div>
                </div>
            </div>
            <div slot="sku-actions">
                <van-button @click="onSubmit" type="primary" bottomAction>确定</van-button>
            </div>
        </van-sku>
        <!--参数弹出层 start-->
        <van-popup v-model="showParameter" position="bottom" style="max-height: 80%">
            <van-panel title="基本信息" style="font-weight: 900">
                <van-cell-group style="font-weight: 500; font-size: 14px">
                    <template v-for="param in goods.parameter">
                        <van-cell
                                v-for="item in param.generalProperties"
                                :key="item.name"
                        >
                            <span style="color: #888; min-width: 130px; display: inline-block"
                                  v-text="item.name"></span>
                            <span style="color: #555;" v-text="item.value"></span>
                        </van-cell>
                    </template>
                </van-cell-group>
            </van-panel>
            <van-button @click="showParameter=false" type="primary" bottomAction>确定</van-button>
        </van-popup>
        <!--参数弹出层 end-->


    </div>

</template>

<script>
    import bus from '../../bus'
    import {getGoods, listSku} from '../../api/goods'
    import {saveAll} from '../../api/carts'
    import {Toast} from 'vant';
    import goodsSku from './goods-sku'

    export default {
        name: 'goods',
        mixins: [goodsSku],
        props: {
            id: String
        },
        data() {
            return {
                cartSubmitFlag: true,
                bus,
                checkSkuArray: [
                    /* {
                       color: '黑色',
                       stock_num: 18,
                       id: 2258, // skuId，下单时后端需要
                       price: 100,
                       stepperLimit: 10,
                       currentNum: 0,
                       quota: 10,// 限购 限购数(0表示不限购)
                     }*/
                ],
                goods: {
                    title: '美国伽力果（约680g/3个）',
                    freightInfo: '免运费',
                    transactionNum: 19,
                    thumb: [
                        ''
                    ],
                    picture: 'https://img.yzcdn.cn/1.jpg',
                    specifications: [
                        {name: '制式', values: [{name: "全网通", noSelect: false}], selectedValue: '全网通'},
                        {
                            name: '颜色',
                            values: [{name: "极地白", noSelect: true}, {name: "暗夜蓝", noSelect: false}, {
                                name: "星空黑",
                                noSelect: false
                            }],
                            selectedValue: '星空黑'
                        },
                    ]
                },
                skuArray: [],
                showParameter: false
            };
        },
        methods: {
            onClickLeft() {
                this.$router.back(-1);
            },
            onClickHome() {
                this.$router.push('/home');
            },
            formatPrice(price) {
                return '¥' + Number.parseInt(price).toFixed(2);
            },
            onClickCart() {
                this.$router.push('/carts');
            },
            onClickGoShopping() {
                this.cartSubmitFlag = false;
                bus.state.cartSubmitFlag = false;
                this.showBase = true;
            },
            onClickAddCart() {
                this.cartSubmitFlag = true;
                bus.state.cartSubmitFlag = true;
                this.showBase = true;
            },
            onSubmit() {
                // 加购物车
                if (this.cartSubmitFlag) {
                    let shopId = this.goods.shopId;
                    let carts = this.listBuySku().map(sku => ({
                        shopId,
                        skuCode: sku.code,
                        number: sku.currentNum,
                        skuId: sku.id,
                        goodsId: this.id
                    }));
                    saveAll(carts, _ => {
                        Toast('加入购物车成功');
                    });
                } else {
//          立即购买
                    /*let carts = {
                      "id": 13,
                      "name": "山东宏米通讯",
                      "commodity": [{
                        "title": "红米S2",
                        "standard": "全网通/4+64",
                        "color": "铂银灰",
                        "count": 1,
                        "price": 1139,
                        "thumb": "http://image-jinyijia1688-com.oss-cn-beijing.aliyuncs.com/goods_6d07bda1d030458ba971cab04345af11.png",
                        "skuCode": "1.10.315",
                        "shopId": 13,
                        "skuId": 408,
                        "goodsId": 28
                      }],
                    };*/
                    let buy = ({
                        id: this.goods.shopId,
                        name: this.goods.shopName,
                    });
                    buy.commodity = this.listBuySku().map(sku => ({
                        title: sku.name,
                        standard: sku.attributes['制式'] + '/' + sku.attributes['版本'],
                        color: sku.attributes['颜色'],
                        count: sku.currentNum,
                        price: sku.price,
                        thumb: this.goods.picture,
                        skuCode: sku.code,
                        shopId: this.goods.shopId,
                        skuId: sku.id,
                        goodsId: this.id
                    }));
                    bus.state.buyList = [buy];
                    this.$router.push('/order-submit');
                }
                this.showBase = false;
            },
            sorry() {
                Toast('sorry')
            },
            onSelectValue(item, value) {
                if (item.selectedValue === value) {
                    item.selectedValue = ''
                } else {
                    item.selectedValue = value
                }
            },
            getSelectSkuArray() {
                let m = new Map();
                this.goods.specifications.forEach(o => {
                    if (o.selectedValue !== '') {
                        m.set(o.name, o.selectedValue)
                    }
                });
                let len = m.size;
                return this.skuArray.filter(sku => {
                    let i = 0;
                    for (let e of m) {
                        let k = e[0];
                        let v = e[1];
                        if (sku.attributes[k] === v) {
                            i++;
                        }
                    }
                    return i === len;
                });
            },
            listBuySku() {
                return this.skuArray.filter(sku => sku.currentNum > 0);
            }
        },
        filters: {
            formatPrice(price) {
                return '¥' + Number.parseInt(price).toFixed(2);
            },
        },
        computed: {
            selectSkuArray() {
                return this.getSelectSkuArray();
            },
            priceRange() {
                let priceArray = this.getSelectSkuArray().map(o => o.price);
                let maxInNumbers = Math.max.apply(Math, priceArray);
                let minInNumbers = Math.min.apply(Math, priceArray);
                return maxInNumbers === minInNumbers ? this.formatPrice(minInNumbers) : this.formatPrice(minInNumbers) + '-' + this.formatPrice(maxInNumbers);
            }
        },
        mounted() {
            getGoods(this.id, data => {
                this.goods = data;
                // 为图片设置最大宽度 防止超出
                setTimeout(() => {
                    let imgs = this.$refs['goods-description'].getElementsByTagName('img');
                    for (let el of imgs) {
                        el.style.cssText = 'max-width:100%';
                    }
                }, 200)
            });
            listSku(this.id, data => {
                this.skuArray = data;
            });
        }
    };
</script>

<style lang="less" scoped>
    .arrow-left {
        margin-left: 15px;
        color: #CCCCCC;
        font-weight: 700
    }

    .home {
        float: right;
        margin-right: 15px;
        color: #CCCCCC;
        font-weight: 700
    }
    .goods {
        margin-bottom: 50px;
        &-swipe {
            img {
                width: 7.5rem;
                height: 7.5rem;
                display: block;
            }
        }

        &-title {
            font-size: 16px;
        }
        &-sub-title {
            font-size: 12px;
        }
        &-price {
            color: #f44;
        }

        &-express {
            color: #999;
            font-size: 12px;
            padding: 5px 15px;
        }

        &-cell-group {
            margin: 15px 0;

            .van-cell__value {
                color: #999;
            }
        }

        &-description {
            img {
                max-width: 100%;
            }
        }
        &-tag {
            margin-left: 5px;
        }

        .van-goods-action {
            z-index: 10;
        }
    }
</style>
